package com.tfleo.mealssenger;

import com.github.ignition.core.widgets.RemoteImageView;
import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.adapter.CommentListAdapter;
import com.tfleo.mealssenger.adapter.FoodListAdapter;
import com.tfleo.mealssenger.object.Comment;
import com.tfleo.mealssenger.object.Food;
import com.tfleo.mealssenger.object.Place;
import com.tfleo.mealssenger.utility.DataFetcher;
import com.tfleo.mealssenger.utility.IntentExtras;
import com.tfleo.mealssenger.utility.PlaceIconFetcher;
import com.tfleo.mealssenger.utility.StaticMapFetcher;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TabHost;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Place page. User can check-in, add comment, and add new food.
 * 
 * @author Theodore Felix Leo
 *
 */
public class PlaceActivity extends Activity implements OnTabChangeListener {
	private static final int SHOW_FOOD_REQ = 1;
	private static final int ASK_HANGOUT_REQ = 2;
	private static final int ADD_FOOD_REQ = 3;
	private static final long FIVE_HOUR = 5*3600*1000; //checkin duration
	private LayoutInflater mInflater;

	private ListView vFoodList;
	private ListView vCommentList;
	private TextView vPlaceName;
	private TextView vPlaceAddress;
	private TextView vPlaceDescription;
	private TextView vPlaceCategory;
	private TextView vPlaceNumCheckin;
	private Button vAddCommentButton;
	private Button vCheckinButton;
	private Button vHangoutButton;
	private RatingBar vRating;
	private RemoteImageView vMapImage;
	
	private int mPlaceId = 0;
	private String mPlaceName;
	private String mPlaceAddress;
	private String mPlaceDescription;
	private String mPlaceCategory;
	private String mPlaceMap;
	private int mPlaceNumCheckin;
	private Float mPlaceLon;
	private Float mPlaceLat;
	private float mCommentRating = 0;
	private float mPlaceRating = 0;
	
	private ArrayList<Food> mFoodList;
	private ArrayList<Comment> mCommentList;
	
	public static final int ADD_FOOD = Menu.FIRST;
	
	private TabHost mTabHost;
	private TabSpec mTabSpec;
	
	private Context mContext;
	
	private CommentListAdapter mCommentAdapter;
	private FoodListAdapter mFoodAdapter;
	
	private SharedPreferences mUserPref;
	private SharedPreferences.Editor mPrefEditor;

	private String mAuth;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.place_layout);
		mContext = this;
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mAuth = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); //for authentication
		
		mUserPref = getSharedPreferences(Main.USER_DATA, MODE_PRIVATE);
		mPrefEditor = mUserPref.edit();
		
		mTabHost = (TabHost) findViewById(R.id.tab);
		mTabHost.setup();
		
		setupTab(new TextView(this), "Menu", R.drawable.icon);
        setupTab(new TextView(this), "Comment", R.drawable.icon);
        
        //Workaround for bug first listview shown doesn't function properly
        mTabHost.setCurrentTab(1);
        mTabHost.setCurrentTab(0);
		
		//Get intent extras
		Bundle extras = getIntent().getExtras();
        if(extras != null) {
        	mPlaceId = extras.getInt(IntentExtras.PLACE_ID);
        	mPlaceName = extras.getString(IntentExtras.PLACE_NAME);
        	mPlaceAddress = extras.getString(IntentExtras.PLACE_ADDR);
        	mPlaceDescription = extras.getString(IntentExtras.PLACE_DESC);
        	mPlaceMap = extras.getString("map");
        	mPlaceCategory = extras.getString(IntentExtras.PLACE_CAT);
        	mPlaceRating = extras.getFloat(IntentExtras.PLACE_RATING, -1);
        	mPlaceLon = extras.getFloat("lon", -255);
        	mPlaceLat = extras.getFloat("lat", -255);
        } else {
        	Toast.makeText(mContext, "Error: Bundle is null!", Toast.LENGTH_SHORT).show();
        	finish();
        }
        
        if(mPlaceId == 0) {
        	Toast.makeText(mContext, "Error: No place referred!", Toast.LENGTH_SHORT).show();
        	finish();
        }
        
        if(mPlaceName == null || mPlaceAddress == null || mPlaceDescription == null || mPlaceMap == null
        		|| mPlaceCategory == null || mPlaceRating == -1 || mPlaceLon == -255 || mPlaceLat == -255) {
        	FetchPlaceTask placeTask = new FetchPlaceTask();
        	placeTask.execute(mPlaceId);
        } else {
        	//Setup views
            vPlaceName = (TextView) findViewById(R.id.name);
            vPlaceName.setText(mPlaceName);
            
            vPlaceAddress = (TextView) findViewById(R.id.address);
            vPlaceAddress.setText(mPlaceAddress);
            
            vPlaceDescription = (TextView) findViewById(R.id.description);
            vPlaceDescription.setText(mPlaceDescription);
            
            vPlaceCategory = (TextView) findViewById(R.id.category);
            vPlaceCategory.setText(mPlaceCategory);
            vPlaceCategory.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(
            		PlaceIconFetcher.getIcon(mPlaceCategory)), null, null, null);
            
            vPlaceNumCheckin = (TextView) findViewById(R.id.num_checkin);
            vPlaceNumCheckin.setText(Integer.toString(mPlaceNumCheckin) + " check-in");
            
            vRating = (RatingBar) findViewById(R.id.rating);
            vRating.setRating(mPlaceRating);
            
            vMapImage = (RemoteImageView) findViewById(R.id.map_img);
            //vMapImage.setImageUrl(StaticMapFetcher.getStaticMapUrl(Float.toString(mPlaceLon), 
    		//		Float.toString(mPlaceLat)));
            vMapImage.setImageUrl(StaticMapFetcher.getFromLocal(mPlaceMap));
    		vMapImage.loadImage();
        }
        
        //Fetch data of foods and comments
        FetchFoodTask foodTask = new FetchFoodTask();
        foodTask.execute(mPlaceId);
        
        FetchCommentTask commentTask = new FetchCommentTask();
        commentTask.execute(mPlaceId);
          
        vCheckinButton = (Button) findViewById(R.id.checkin_btn);
        vCheckinButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddCheckinTask checkinTask = new AddCheckinTask();
				checkinTask.execute(new String[]{
	            		String.valueOf(mUserPref.getInt(Main.USER_ID, 0)),
	            		mUserPref.getString(Main.USER_NAME, ""),
	            		String.valueOf(mPlaceId),
	            		mPlaceName
	            });
			}
        });
        
        vHangoutButton = (Button) findViewById(R.id.hangout_btn);
        vHangoutButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(mContext, AskHangoutActivity.class);
				i.putExtra("id", mPlaceId);
				i.putExtra("name", mPlaceName);
				i.putExtra("category", mPlaceCategory);
				i.putExtra("map", mPlaceMap);
				i.putExtra("lon", Float.toString(mPlaceLon));
				i.putExtra("lat", Float.toString(mPlaceLat));
				startActivityForResult(i, ASK_HANGOUT_REQ);
			}
        });
        
        //Check last checkin
        VerifyLastCheckinTask lastCheckinTask = new VerifyLastCheckinTask();
        lastCheckinTask.execute(mUserPref.getInt(Main.LAST_CHECKIN_ID, 0), mPlaceId, 
        		mUserPref.getInt(Main.USER_ID, 0));
        
        
        vAddCommentButton = (Button) findViewById(R.id.add_comment_btn);
        vAddCommentButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				buildCommentDialog();
			}
        });
        
	}
	
	@Override
	public void onResume() {
		super.onResume();
//		mCommentList = DataFetcher.fetchFoodComment(mPlaceId);
//		mCommentAdapter.notifyDataSetChanged();
//		
//		mFoodList = DataFetcher.fetchPlaceFoods(mPlaceId);
//		mFoodAdapter.notifyDataSetChanged();
	}
	
	/**
     * Setup each tab specification
     * 
     * @param view
     * @param tag
     * @param icon
     */
    private void setupTab(View view, String tag, int icon) {
    	View tabview = createTabView(mTabHost.getContext(), tag, icon);
    	if(tag.equals("Menu")) {
	    	mTabSpec = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
	        	public View createTabContent(String arg0) {
	                vFoodList = (ListView) findViewById(R.id.food_list);
					return vFoodList;
				}
	    	});
    	} else {
    		mTabSpec = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
	        	public View createTabContent(String arg0) {
	                vCommentList = (ListView) findViewById(R.id.comment_list);
					return vCommentList;
				}
	    	});
    	}
    	mTabHost.addTab(mTabSpec);
    }
    
    /**
     * Setup view on tab bar
     * 
     * @param context
     * @param text
     * @param icon
     * @return View to be shown on tab bar
     */
    private static View createTabView(Context context, String text, int icon) {
    	View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg_text, null);
    	
    	TextView tv = (TextView) view.findViewById(R.id.tabs_text);
    	tv.setText(text);
  
    	return view;
    }
   
    
    private boolean addCheckin(int userId, String userName, int placeId, String placeName) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "place/" + mPlaceId + "/checkin");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(userId)));
			nameValuePairs.add(new BasicNameValuePair("user_name", userName));
			//nameValuePairs.add(new BasicNameValuePair("place_id", Integer.toString(placeId)));
			nameValuePairs.add(new BasicNameValuePair("place_name", placeName));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String body = httpclient.execute(httppost, responseHandler);
			JSONObject jo = new JSONObject(body);
			int lastInsertId;
			if((lastInsertId = jo.getInt("code")) > 0) {
				mPrefEditor.putInt(Main.LAST_CHECKIN_ID, lastInsertId);
				mPrefEditor.putInt(Main.LAST_CHECKIN_PLACEID, placeId);
				mPrefEditor.putString(Main.LAST_CHECKIN_PLACENAME, placeName);
				mPrefEditor.commit();
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
    
    private boolean addComment(int userId, String userName, int placeId, float rating, String content) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "place/" + mPlaceId + "/postcomment");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(userId)));
			//nameValuePairs.add(new BasicNameValuePair("place_id", Integer.toString(placeId)));
			nameValuePairs.add(new BasicNameValuePair("rating", Float.toString(rating)));
			nameValuePairs.add(new BasicNameValuePair("comment", content));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String body = httpclient.execute(httppost, responseHandler);
			JSONObject jo = new JSONObject(body);
			if((jo.getInt("code")) > 0) {
				mCommentList = DataFetcher.fetchPlaceComment(placeId);
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
    
    private boolean isLastCheckedPlace(int checkinId, int placeId, int userId) {
    	if(checkinId == 0) {
    		return false;
    	}
		try {
			URL url = new URL(Main.SERVER_URL + "checkin/" + checkinId);
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			String body;
			while ((body = in.readLine()) != null) {
				JSONObject jo = new JSONObject(body);
				
				if(jo.getInt("code") == 1) {
					JSONObject response = jo.getJSONObject("response");
					boolean recent = true;
					mPlaceNumCheckin = jo.getInt("num_checkin");
					String fullDateTime = response.getString("date");
					String[] splitDateTime = fullDateTime.split(" ");
					
					String[] splitDate = splitDateTime[0].split("-");
					String[] splitTime = splitDateTime[1].split(":");
					
					int year = Integer.parseInt(splitDate[0]);
					int month = Integer.parseInt(splitDate[1]);
					int day = Integer.parseInt(splitDate[2]);
					int hour = Integer.parseInt(splitTime[0]);
					int minute = Integer.parseInt(splitTime[1]);
					
					Calendar c = Calendar.getInstance();
					GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, minute);
					
					if(c.getTimeInMillis() - gc.getTimeInMillis() > FIVE_HOUR) {
						recent = false;
					}

					if(recent && (placeId == response.getInt("place_id")) && 
							(userId == response.getInt("user_id"))) {
						return true;
					} else {
						return false;
					}
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return false;
    }
    
    private void buildCommentDialog() {
		View layout = mInflater.inflate(R.layout.add_comment, null);
	    final EditText vContent = (EditText) layout.findViewById(R.id.comment_content);
	    final RatingBar ratingbar = (RatingBar) layout.findViewById(R.id.rating);
	    ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
	        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
	            mCommentRating = rating;
	        }
	    });
	    //Building dialog
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setView(layout);
	    
	    builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        	if(vContent.getText().toString().trim().equals("")) {
	        		Toast.makeText(mContext, "Error: Empty comment!", Toast.LENGTH_SHORT).show();
	        		return;
	        	}

	            AddCommentTask addCommentTask = new AddCommentTask();
	            String[] data = new String[]{
	            		String.valueOf(mUserPref.getInt(Main.USER_ID, 0)),
	            		mUserPref.getString(Main.USER_NAME, ""),
	            		String.valueOf(mPlaceId),
	            		String.valueOf(mCommentRating),
	            		vContent.getText().toString().trim()
	            };
	            addCommentTask.execute(data);
	        }
	    });
	    
	    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	            dialog.dismiss();
	        }
	    });
	    
	    AlertDialog dialog = builder.create();
		dialog.setTitle("Add comment");
		dialog.show();
		
		ViewGroup parent = (ViewGroup)layout.getParent();
		parent.setPadding(0, 0, 0, 1);
	}
    
    private class VerifyLastCheckinTask extends AsyncTask<Integer, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... id) {
			int checkinId = id[0];
			int placeId = id[1];
			int userId = id[2];
			
			return isLastCheckedPlace(checkinId, placeId, userId);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				vCheckinButton.setText("Checked in");
				vCheckinButton.setEnabled(false);
				vCheckinButton.setBackgroundColor(Color.parseColor("#00000000"));
				vCheckinButton.setTextColor(getResources().getColor(R.color.dark_brown));
				
				vPlaceNumCheckin.setText(Integer.toString(mPlaceNumCheckin) + " check-in");
    		}
			vCheckinButton.setVisibility(View.VISIBLE);
	    }
	}
	
    private class FetchPlaceTask extends AsyncTask<Integer, Void, Place> {	
		@Override
		protected Place doInBackground(Integer... id) {
			int placeId = id[0];
			
			return DataFetcher.fetchPlace(placeId);
			
		}
		
		@Override
		protected void onPostExecute(Place result) {
			if(result != null) {
				mPlaceName = result.name;
	        	mPlaceAddress = result.address;
	        	mPlaceDescription = result.description;
	        	mPlaceMap = result.image;
	        	mPlaceCategory = result.category;
	        	mPlaceRating = result.rating;
	        	mPlaceLon = result.longitude;
	        	mPlaceLat = result.latitude;
	        	mPlaceNumCheckin = result.numCheckin;
	        	
	        	//Setup views
	            vPlaceName = (TextView) findViewById(R.id.name);
	            vPlaceName.setText(mPlaceName);
	            
	            vPlaceAddress = (TextView) findViewById(R.id.address);
	            vPlaceAddress.setText(mPlaceAddress);
	            
	            vPlaceDescription = (TextView) findViewById(R.id.description);
	            vPlaceDescription.setText(mPlaceDescription);
	            
	            vPlaceCategory = (TextView) findViewById(R.id.category);
	            vPlaceCategory.setText(mPlaceCategory);
	            vPlaceCategory.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(
	            		PlaceIconFetcher.getIcon(mPlaceCategory)), null, null, null);
	            
	            vPlaceNumCheckin = (TextView) findViewById(R.id.num_checkin);
	            vPlaceNumCheckin.setText(Integer.toString(mPlaceNumCheckin) + " check-in");
	            
	            vRating = (RatingBar) findViewById(R.id.rating);
	            vRating.setRating(mPlaceRating);
	            
	            vMapImage = (RemoteImageView) findViewById(R.id.map_img);
	            //vMapImage.setImageUrl(StaticMapFetcher.getStaticMapUrl(Float.toString(mPlaceLon), 
	    		//		Float.toString(mPlaceLat)));
	            vMapImage.setImageUrl(StaticMapFetcher.getFromLocal(mPlaceMap));
	    		vMapImage.loadImage();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    		}
	    }
	}
       
    private class FetchFoodTask extends AsyncTask<Integer, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Loading...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(Integer... id) {
			int placeId = id[0];
			
			mFoodList = DataFetcher.fetchMenu(placeId);
			if(mFoodList == null) {
				return false;
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mFoodAdapter = new FoodListAdapter(mContext, R.layout.food_entry, 
        				R.id.name, mFoodList, mInflater);
                vFoodList.setAdapter(mFoodAdapter);
                vFoodList.setOnItemClickListener(new OnItemClickListener() {
                	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {         
                		Intent i = new Intent(PlaceActivity.this, FoodActivity.class); 
                		i.putExtra("id", mFoodList.get(position).id);
                		i.putExtra("name", mFoodList.get(position).name); 
                		i.putExtra("location_id", mFoodList.get(position).locationId);
                		i.putExtra("location_name", mFoodList.get(position).locationName);
                		i.putExtra("description", mFoodList.get(position).description);
                		i.putExtra("image", mFoodList.get(position).imageUrl);
                		i.putExtra("category", mFoodList.get(position).category);
                		i.putExtra("likes", mFoodList.get(position).numEaten);
                		i.putExtra("rating", mFoodList.get(position).rating);
                		startActivityForResult(i, SHOW_FOOD_REQ);
                	}
                });
				mProgressDialog.dismiss();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    			mProgressDialog.dismiss();
    		}
	    }
	}
    
    private class FetchCommentTask extends AsyncTask<Integer, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Loading...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(Integer... id) {
			int placeId = id[0];
			
			mCommentList = DataFetcher.fetchPlaceComment(placeId);
			if(mCommentList == null) {
				return false;
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mCommentAdapter = new CommentListAdapter(mContext, R.layout.comment_list_entry, 
						R.id.name, mCommentList, mInflater);
                vCommentList.setAdapter(mCommentAdapter);
        		
				mProgressDialog.dismiss();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    			mProgressDialog.dismiss();
    		}
	    }	
	}
    
    private class AddCommentTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected Boolean doInBackground(String... data) {
			int userId = Integer.valueOf(data[0]);
			String userName = data[1];
			int placeId = Integer.valueOf(data[2]);
			float rating = Float.valueOf(data[3]);
			String content = data[4];
			
			return addComment(userId, userName, placeId, rating, content);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mCommentAdapter = new CommentListAdapter(mContext, R.layout.comment_list_entry, 
						R.id.name, mCommentList, mInflater);
				vCommentList.setAdapter(mCommentAdapter);
    		} else {
    			Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
    		}
	    }	
	}
    
    private class AddCheckinTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected Boolean doInBackground(String... data) {
			int userId = Integer.valueOf(data[0]);
			String userName = data[1];
			int placeId = Integer.valueOf(data[2]);
			String placeName = data[3];
			
			return addCheckin(userId, userName, placeId, placeName);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mPlaceNumCheckin++;
				vCheckinButton.setText("Checked in");
				vCheckinButton.setEnabled(false);
				vCheckinButton.setBackgroundColor(Color.parseColor("#00000000"));
				vCheckinButton.setTextColor(getResources().getColor(R.color.dark_brown));
				
				vPlaceNumCheckin.setText(Integer.toString(mPlaceNumCheckin) + " check-in");
			} else {
				Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
			}
	    }	
	}
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.place_menu, menu);
		return result;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.add_food:
			addFood();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void addFood() {
		Intent i = new Intent(this, AddFoodActivity.class);
		i.putExtra(IntentExtras.PLACE_ID, mPlaceId);
		i.putExtra(IntentExtras.PLACE_NAME, mPlaceName);
		startActivityForResult(i, ADD_FOOD_REQ);
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		switch(requestCode) {
		case SHOW_FOOD_REQ:
		case ADD_FOOD_REQ:
			mFoodList = DataFetcher.fetchMenu(mPlaceId);
			mFoodAdapter = new FoodListAdapter(mContext, R.layout.food_entry, 
    				R.id.name, mFoodList, mInflater);
			vFoodList.setAdapter(mFoodAdapter);
			break;
		default:
			//TODO:	
		}
	}
	
	public void onTabChanged(String arg0) {
		
	}

}
